package cn.fl.project.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.cache.framework.redis.RedisHelper;
import cn.fl.commons.result.ResponseData;
import cn.fl.preloan.IPrjContCreatRecApiService;
import cn.fl.project.api.IProjectContractMakeApiService;
import cn.fl.project.condition.PrjContCreatRecQueryCondition;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.dto.PrjContCreatRecDTO;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjContBatchMakeService;
import cn.fl.project.vo.PrjBscInfoVO;
import com.google.common.collect.Lists;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.fl.project.vo.PrjContCreatRecVO;
import cn.fl.framework.base.context.CurrentThreadContext;

import cn.fl.system.constant.SysLogConstant;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;

/**
 * @Description: 项目合同生成记录表 控制层
 */
@Controller
@RequestMapping("/project/prjContCreatRec")
public class PrjContCreatRecController extends BaseController {
	private static final String REDIS_FILTER_COUNT_KEY = "cont_addFilterContTemplate";
	private static final Logger logger = LoggerFactory.getLogger(PrjContCreatRecController.class);

	/**
	 * PrjContCreatRec 服务层BEAN
	 */
	@Autowired
	private IPrjContBatchMakeService prjContBatchMakeService;

	@Autowired
	private IProjectContractMakeApiService projectContractMakeApiService;

	@Autowired
	private IPrjBscInfoService prjBscInfoService;

	@Autowired
	private IPrjContCreatRecApiService prjContCreatRecApiService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("project/prjcontBatchMake/prjContBatchMake");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	/**
	 * 获取常量
	 */
	@RequestMapping(value = "/selectFilterContTemplate.do")
	public @ResponseBody DataResultVO selectFilterContTemplate() {
		Object addFilterContTemplate = RedisHelper.get(REDIS_FILTER_COUNT_KEY);
        DataResultVO dataResultVO = new DataResultVO();
        dataResultVO.setInfo("设置成功");
        dataResultVO.setData(String.valueOf(addFilterContTemplate));
        return dataResultVO;
	}

	/**
	 * 设置常量
	 */
	@RequestMapping(value = "/addFilterContTemplate.do")
	public @ResponseBody DataResultVO addFilterContTemplate(String templateId) {
		RedisHelper.set(REDIS_FILTER_COUNT_KEY,templateId);
        DataResultVO dataResultVO = new DataResultVO();
        dataResultVO.setInfo("设置成功");
		return dataResultVO;
	}

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListLogPage.do", method = { RequestMethod.GET})
	public ModelAndView toListLogPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("project/prjcontBatchMake/prjContBatchMakeList");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	@RequestMapping(value = "/addContByBatchNumber.do", method = {RequestMethod.POST})
	@ResponseBody
	public DataResultVO addContByBatchNumber(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
		BaseLogUtils.info(logger, "addContByBatchNumber", "批量创建合同Start", CurrentThreadContext.getCurrentUserName());
		try {
			String batchNumber = request.getParameter("batchNumber");
			if(StringUtils.isNotBlank(batchNumber)){
				this.prjContBatchMakeService.addContByBatchNumber(batchNumber);
				result.setData(batchNumber);
			}else{
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("批号不能为空");
			}

		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "addContByBatchNumber", "批量创建合同失败", CurrentThreadContext.getCurrentUserName(), ex);
		} catch (IllegalStateException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "addContByBatchNumber", "批量创建合同失败", CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;

	}


	@RequestMapping(value = "/addContractByLogId.do", method = {RequestMethod.POST})
	@ResponseBody
	public DataResultVO addContractByLogId(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
		try {
			String logId = request.getParameter("logId");
			String templateId = request.getParameter("templateId");
			if(StringUtils.isNotBlank(logId)){
				//暂时这样处理 等全部切到贷前服务在做调整 直接调用prjContCreatRecApiService.addContractByPrjContCreatRecId方法就行
				PrjContCreatRecDTO prjContCreatRecDTO = projectContractMakeApiService.selectById(Long.valueOf(logId));
				if (prjContCreatRecDTO == null || StringUtils.isEmpty(prjContCreatRecDTO.getPrjId())) {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("未查到该记录");
					return result;
				}
				PrjBscInfoVO prjBscInfoVO = prjBscInfoService.selectById(prjContCreatRecDTO.getPrjId());
				if (prjBscInfoVO != null && (PrjBscInfoConstant.PRJ_INS_CODE_SHNS.equals(prjBscInfoVO.getInsCode())
						|| PrjBscInfoConstant.PRJ_INS_CODE_ZBBANKX.equals(prjBscInfoVO.getInsCode())
						|| PrjBscInfoConstant.PRJ_INS_CODE_APFL.equals(prjBscInfoVO.getInsCode())
						|| PrjBscInfoConstant.PRJ_INS_CODE_YLBANK.equals(prjBscInfoVO.getInsCode())
						|| PrjBscInfoConstant.PRJ_INS_CODE_SSFL.equals(prjBscInfoVO.getInsCode())
						|| (PrjBscInfoConstant.PRJ_INS_CODE_SPD.equals(prjBscInfoVO.getInsCode()) &&
							(PrjBscInfoConstant.CODE_BU_ORG_CD_ZK.equals(prjBscInfoVO.getBuOrgCd()) || PrjBscInfoConstant.CODE_BU_ORG_CD_ZC.equals(prjBscInfoVO.getBuOrgCd()) || PrjBscInfoConstant.CODE_BU_ORG_CD_XNY.equals(prjBscInfoVO.getBuOrgCd())))
						|| PrjBscInfoConstant.PRJ_INS_CODE_ICBCQD.equals(prjBscInfoVO.getInsCode())
						|| PrjBscInfoConstant.PRJ_INS_CODE_PABANK.equals(prjBscInfoVO.getInsCode())
						|| PrjBscInfoConstant.PRJ_INS_CODE_BOCBTBANK.equals(prjBscInfoVO.getInsCode())
				)) {
					List<String> tmplateIds = new ArrayList<>();
					if (StringUtils.isNotEmpty(templateId)) {
						String[] split = templateId.split(",");
						Collections.addAll(tmplateIds, split);
					}
					ResponseData responseData = prjContCreatRecApiService.addContractByPrjContCreatRecId(Long.valueOf(logId), tmplateIds, CurrentThreadContext.getCurrentUserId());
					if (!"1".equals(responseData.getCode()) || !responseData.isSuccess()) {
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo(responseData.getMessage());
						return result;
					}
				} else {
					if (StringUtils.isNotEmpty(templateId)) {
						String[] split = templateId.split(",");
						this.prjContBatchMakeService.addContract(Long.valueOf(logId), Lists.newArrayList(split));
					} else {
						this.prjContBatchMakeService.addContractByLogId(Long.valueOf(logId));
					}
				}

				result.setData(logId);
			}else{
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("记录id不能为空");
			}

		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "addContractByLogId", "创建合同失败", CurrentThreadContext.getCurrentUserName(), ex);
		} catch (IllegalStateException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "addContractByLogId", "创建合同失败", CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;

	}

	@RequestMapping(value = "/addBatchByUpload.do", method = {RequestMethod.POST})
	@ResponseBody
	public DataResultVO addBatchByUpload(MultipartHttpServletRequest multipartRequest) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
		try {
			String batchNumber = this.prjContBatchMakeService.addBatchByUpload(multipartRequest);
			result.setData(batchNumber);
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "upload", "文件上传失败", CurrentThreadContext.getCurrentUserName(), ex);
		} catch (IllegalStateException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "upload", "文件上传失败,系统错误", CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;

	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String forceSign = request.getParameter("forceSign");
		String cfgCd = request.getParameter("cfgCd");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		PrjContCreatRecVO entity = null;
		try {
			entity= new PrjContCreatRecVO();
			if(StringUtils.isNotBlank(forceSign)){
				entity.setForceSign(Integer.valueOf(forceSign));
			}
			if(StringUtils.isNotBlank(cfgCd)){
				entity.setCfgCd(cfgCd);
			}
			entity.setId(Long.valueOf(id));
			boolean success = this.prjContBatchMakeService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	@RequestMapping(value = "/selectListByBatchNumber.do", method = {RequestMethod.POST})
	@ResponseBody
	public DataResultVO selectListByBatchNumber(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String batchNumber = request.getParameter("batchNumber");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
		try {
			if(org.apache.commons.lang3.StringUtils.isBlank(batchNumber)){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("生产批号不能为空");
			}else{
				List<PrjContCreatRecVO> prjContBatchMakeVos = this.prjContBatchMakeService.selectListByBatchNumber(batchNumber);
				result.setData(prjContBatchMakeVos);
			}

		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "upload", "查询数据失败", CurrentThreadContext.getCurrentUserName(), ex);
		} catch (IllegalStateException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "upload", "查询数据失败,系统错误", CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;

	}

	@RequestMapping(value = "/initList.do", method = {RequestMethod.POST})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "initList", "加载例子列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String searchName = request.getParameter("batchNumber");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(currentPage)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		PrjContCreatRecQueryCondition qc = new PrjContCreatRecQueryCondition();
		if (StringUtils.isNotEmpty(searchName)) {
			qc.setBatchNo(searchName);
		}
		page.setCondition(qc);

		Pager pager = this.prjContBatchMakeService.searchListPage(page);
		List<PrjContCreatRecVO> list = (List<PrjContCreatRecVO>) pager.getResultList();
		ListPageVO<PrjContCreatRecVO> listPage = new ListPageVO<PrjContCreatRecVO>(list, pager.getTotalCount());

		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "initList", "加载例子列表页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return listPage;

	}
}

